package net.sourceforge.krama.tag;

import java.util.List;

import net.sourceforge.krama.util.TUtil;
import net.sourceforge.krama.xml.TXMLLoader;

import org.apache.commons.lang.StringUtils;
import org.jdom.Document;

/**
 * 
 * @author chabane
 *
 */
public abstract class Ajax {
	/**
	 * This method allows to build a javascript fonction for generate javascript code later
	 * @param classe
	 * @param methode
	 * @param params
	 * @return String
	 */
	public static String show(String classe, String methode, List params) {

		String paramFonction = "";
		String rawTable = "";
		TXMLLoader kramaInstance = TXMLLoader.getInstance();
		Document document = kramaInstance.openkramaConfig(TLib.getConfigXML());

		if (TUtil.stringOk(classe) && TUtil.stringOk(methode)) {

			if (kramaInstance.checkAjaxInformation(document, classe, methode,
					params)) {

				paramFonction = "'" + classe + "'";
				paramFonction += ",'" + methode + "'";

				if (TUtil.listOk(params)) {

					for (int r = 0; r < params.size(); r++) {
						if (params.get(r) == null || StringUtils.isEmpty(params.get(r).toString()))
							params.set(r, "null");
						if (r == params.size() - 1)
							rawTable += "'" + params.get(r) + "'";
						else
							rawTable += "'" + params.get(r) + "',";
					}
					paramFonction += ", [" + rawTable + "]";
				} else {
					paramFonction += ", []";
				}
			} else
				throw new IllegalArgumentException();
		} else
			throw new IllegalArgumentException();
		TUtil.javascriptShouldBeAvailable = true;
		TUtil.prototypeShouldBeAvailable = true;
		TUtil.clicShouldBeAvailable = true;
		return paramFonction;
	}
}
